package com.treasure.mall.zbqmallapi.controller;

import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.oss.Attachment;
import com.treasure.mall.zbq.common.oss.ResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.UUID;

/**
 * All rights Reserved, Designed By ustyle_server
 * +---------------------------------------------------------
 * * @package: cn.ustyle.server.api.controller.upload
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/4/20 18:31
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 cn.ustyle.server.api.controller.upload Inc. All rights reserved.
 */
@Api(tags = "上传模块")
@RestController
public class ResourceController {
    private static final String IMG_SUFFIX_PATH = "image/";
    @javax.annotation.Resource
    private ResourceService resourceService;

    /**
     * @param file 上传文件
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    @ApiOperation("文件上传")
    @PostMapping("/uploadTempResource")
    public ApiResult uploadFile(@RequestParam(value = "data", required = false) MultipartFile file
    ) {
        try {
            //上传文件
            if (file != null) {
                String fileName = file.getOriginalFilename();
                assert fileName != null;
                String prefix = fileName.substring(fileName.lastIndexOf("."));
                String savePath = IMG_SUFFIX_PATH + UUID.randomUUID().toString().replaceAll("-", "")
                        + prefix;
                Resource resource = resourceService.upload(savePath, file.getInputStream());
                Attachment attachment = new Attachment();
                attachment.setPreviewUrl(resource.getURI().toString());
                attachment.setPath(resource.getURI().toString());
                return ApiResult.ok(attachment);
            }
        } catch (Exception e) {
            return ApiResult.error(e.getMessage());
        }
        return ApiResult.error("请上传文件...");
    }
}
